//
//  uSurGroupViewController.m
//  wAudioShare
//
//  Created by 赵帅 on 14-3-6.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "uSurGroupViewController.h"
#import "WiimuUpnp.h"
#import "SurGroupObject.h"
#import "uSurGroupOperationViewController.h"

@interface uSurGroupViewController ()
<WiimuUpnpDelegate,serviceGetGroupNameDelegate,serviceAddAudioToGroupDelegate,uGroupOperationDatasource,uGroupOperationDelegate>
{
    NSMutableArray * deviceArr;
    NSMutableArray * groupArr;
    
    NSTimer * timer;
}

@property (assign) IBOutlet UITableView * menuView;

@end

@implementation uSurGroupViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[WiimuUpnp sharedInstance] addDelegate:self];
    [[WiimuUpnp sharedInstance] refresh];
    
    deviceArr = [[NSMutableArray alloc] init];
    groupArr = [[NSMutableArray alloc] init];
    
    timer = [NSTimer timerWithTimeInterval:4 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigation methods
-(NSString *)navigationBarTitle
{
    return @"Multiroom";
}


//#pragma mark -
//#pragma mark UITableView Delegate & Datasource
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 60;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return [deviceArr count];
//}
//
//// Customize the appearance of table view cells.
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    static NSString *CellIdentifier = @"Cell";
//    
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//    }
//    else
//    {
//        for(UIView * subview in [cell.contentView subviews])
//        {
//            [subview removeFromSuperview];
//        }
//    }
//    
//    // Configure the cell.
//    
//    NSDictionary * dic = [deviceArr objectAtIndex:indexPath.row];
//    
//    UIImageView * imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"upnpdevice.png"]];
//    [cell.contentView addSubview:imageview];
//    [imageview setFrame:CGRectMake(10, 10, 40, 40)];
//    
//    UILabel * label = [[UILabel alloc] init];
//    label.frame = CGRectMake(60, 10, 200, 40);
//    [cell.contentView addSubview:label];
//    label.backgroundColor = [UIColor clearColor];
//    label.text = dic[@"friendlyName"];
//    
//    UIImageView * rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rightarrow1.png"]];
//    rightImage.frame = CGRectMake(tableView.frame.size.width-40, 20, 10, 20);
//    [cell.contentView addSubview:rightImage];
//    
//    return cell;
//}
//
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
//    
//    NSDictionary * dic = [deviceArr objectAtIndex:indexPath.row];
//    
//    NSRange endRange = [dic[@"baseURL"] rangeOfString:@":" options:NSBackwardsSearch];
//    
//    if(endRange.location == NSNotFound)
//    {
//        return;
//    }
//    
//    NSString * baseUrl = [dic[@"baseURL"] substringToIndex:endRange.location];
//    
//
//}

#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [groupArr count]+1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == [groupArr count]) return 0;
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == [groupArr count])
    {
        return nil;
    }
    
    UIView * av = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
    av.backgroundColor = [UIColor lightGrayColor];
    
    UIImageView * imagev = [[UIImageView alloc] initWithFrame:CGRectMake(5, 7, 30, 30)];
    imagev.image = [UIImage imageNamed:@"multiroom_group"];
    [av addSubview:imagev];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    SurGroupObject * obj = groupArr[section];
    titleLabel.frame = CGRectMake(45, 0, 215, 45);
    titleLabel.text = obj.groupName;
    [av addSubview:titleLabel];
    
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(self.menuView.frame.size.width-52, 5, 45, 45)];
    [button setImage:[UIImage imageNamed:@"multiroom_add"] forState:UIControlStateNormal];
    [button setImageEdgeInsets:UIEdgeInsetsMake(6, 10, 14, 10)];
    button.tag = section;
    [button addTarget:self action:@selector(addDeviceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [av addSubview:button];
    
    return av;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section != [groupArr count])
    {
        SurGroupObject * obj = [groupArr objectAtIndex:section];
        return [obj.audioGroup count];
    }
    else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    else
    {
        for(UIView * subview in [cell.contentView subviews])
        {
            [subview removeFromSuperview];
        }
    }
    
    UILabel * titleLabel = [[UILabel alloc] init];
    
    // Configure the cell.
    if(indexPath.section == [groupArr count])
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        titleLabel.font = [UIFont boldSystemFontOfSize:17];
        titleLabel.frame = CGRectMake(self.view.frame.size.width/2-50, 10, 250, 40);
        titleLabel.text = @"添加新预设组";
    }
    else
    {
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
        SurGroupObject * obj = groupArr[indexPath.section];
        titleLabel.frame = CGRectMake(65, 10, 195, 40);
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = obj.audioGroup[indexPath.row];
        titleLabel.font = [UIFont systemFontOfSize:15];
        
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-55, 5, 50, 50)];
        [button setImage:[UIImage imageNamed:@"multiroom_delete"] forState:UIControlStateNormal];
        [button setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
        [button addTarget:self action:@selector(deleteDeviceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:button];
        
        UIImageView * imagev = [[UIImageView alloc] initWithFrame:CGRectMake(25, 15, 30, 30)];
        imagev.image = [UIImage imageNamed:@"topAnimation_device"];
        [cell.contentView addSubview:imagev];
    }
    
    [cell.contentView addSubview:titleLabel];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
    if(indexPath.section == [groupArr count])
    {
        [self enterNewGroupController:nil];
    }
}


#pragma mark - UPNP callbacks
-(void)newDeviceCome:(NSDictionary *)device
{
    [deviceArr addObject:device];
    
    [self.menuView reloadData];
}

-(void)deviceInfoChange:(NSDictionary *)device
{
    for(int i=0; i<[deviceArr count]; i++)
    {
        NSDictionary * dic = [deviceArr objectAtIndex:i];
        
        if([dic[@"friendlyName"] isEqualToString:device[@"friendlyName"]])
        {
            [deviceArr replaceObjectAtIndex:i withObject:device];
            break;
        }
    }
    
    [self.menuView reloadData];
}

-(void)deviceDisappear:(NSDictionary *)device
{
    SurGroupObject * groupObj = [self isInOneGroup:device[@"friendlyName"]];
    [groupObj.audioGroup removeObject:device[@"friendlyName"]];
    if([groupObj.audioGroup count] == 0)
    {
        [groupArr removeObject:groupObj];
    }
    
    int i;
    for(i=0; i<[deviceArr count]; i++)
    {
        NSDictionary * dic = [deviceArr objectAtIndex:i];
        
        if([dic[@"friendlyName"] isEqualToString:device[@"friendlyName"]])
        {
            break;
        }
    }
    
    [deviceArr removeObjectAtIndex:i];
    
    [self.menuView reloadData];
}

-(void)netWorkStatusChanged:(Reachability*) curReach
{
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if(status != ReachableViaWiFi)
    {
        [[WiimuUpnp sharedInstance] stopSSDP];
        
        NSLog(@"请将手机连接到Wi-Fi网络");
        [deviceArr removeAllObjects];
        [self.menuView reloadData];
    }
    else
    {
        [[WiimuUpnp sharedInstance] beginSSDP:devWifiAudio];
    }
}

-(void)allDevicesDisappear
{
    [deviceArr removeAllObjects];
    [self.menuView reloadData];
}

#pragma mark - private methods
-(void)timerMethod
{
    dispatch_async(dispatch_get_main_queue(), ^{
        for(NSDictionary * dic in deviceArr)
        {
            NSString * baseURL = dic[@"baseURL"];
            NSArray * arr = [baseURL componentsSeparatedByString:@"/"];
            NSString * ip = arr[2];
            arr = [ip componentsSeparatedByString:@":"];
            ip = arr[0];
            
            [[GlobalService sharedInstance] getGroupName:self baseURL:ip deviceName:dic[@"friendlyName"]];
        }
    });
}

-(SurGroupObject *)isInOneGroup:(NSString *)name
{
    for(SurGroupObject * obj in groupArr)
    {
        for(NSString * deviceName in obj.audioGroup)
        {
            if([deviceName isEqualToString:name])
            {
                return obj;
            }
        }
    }
    
    return nil;
}

-(void)addDevice:(NSString *)name inGroup:(NSString *)groupName
{
    BOOL isExsit = NO;
    //添加到新组
    for(SurGroupObject * obj in groupArr)
    {
        if([obj.groupName isEqualToString:groupName])
        {
            isExsit = YES;
            [obj.audioGroup addObject:name];
            break;
        }
    }
    
    //建新组
    if(isExsit == NO)
    {
        SurGroupObject * obj = [[SurGroupObject alloc] init];
        obj.groupName = groupName;
        [obj.audioGroup addObject:name];
        
        [groupArr addObject:obj];
    }
    
    [self.menuView reloadData];
}

-(void)enterNewGroupController:(SurGroupObject *)groupObj
{
    uSurGroupOperationViewController * controller = [[uSurGroupOperationViewController alloc] initWithNibName:@"uSurGroupOperationViewController" bundle:nil];
    controller.datasource = self;
    controller.delegate = self;
    controller.groupObj = groupObj;
    [self.navigationController pushViewController:controller animated:YES];
}


-(IBAction)addDeviceButtonPressed:(id)sender
{
    UIButton * bt = (UIButton *)sender;
    SurGroupObject * obj = groupArr[bt.tag];
    [self enterNewGroupController:obj];
}

-(IBAction)deleteDeviceButtonPressed:(id)sender
{
    UIButton * bt = (UIButton *)sender;
    UITableViewCell *cell = nil;
    if([[[UIDevice currentDevice] systemVersion] intValue] >= 7)
    {
        cell = (UITableViewCell *)(bt.superview.superview.superview);
    }
    else
    {
        cell = (UITableViewCell *)(bt.superview.superview);
    }
    
    NSIndexPath *indexPath = [_menuView indexPathForCell:cell];
    
    SurGroupObject * obj = groupArr[indexPath.section];
    NSDictionary * dic = nil;
    for(dic in deviceArr)
    {
        if([dic[@"friendlyName"] isEqualToString:obj.audioGroup[indexPath.row]])
        {
            NSString * baseURL = dic[@"baseURL"];
            NSArray * arr = [baseURL componentsSeparatedByString:@"/"];
            NSString * ip = arr[2];
            arr = [ip componentsSeparatedByString:@":"];
            ip = arr[0];
            
            [[GlobalService sharedInstance] addAudioToGroup:self baseURL:ip groupName:@""];
            break;
        }
    }
}

-(NSArray *)getAllDevices
{
    return deviceArr;
}

-(void)devicesAddToGroup:(NSArray *)array
{

}

#pragma mark - service method
-(void)serviceGetGroupNameCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary * dic = dicCallBack;
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {

        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue] ||
            [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue])
    {
        return;
    }
    
    NSString * groupName = dic[@"group"];
    NSString * deviceName = dic[@"name"];
    
    SurGroupObject * groupObj = [self isInOneGroup:deviceName];
    if(groupObj != nil)
    {
        if([groupName length] == 0)//无groupname从组中删除
        {
            [groupObj.audioGroup removeObject:deviceName];
            if([groupObj.audioGroup count] == 0)
            {
                [groupArr removeObject:groupObj];
            }
            [self.menuView reloadData];
        }
        else if(![groupName isEqualToString:groupObj.groupName])//获得的组名和当前所在的组不一样
        {
            //从旧组删除
            [groupObj.audioGroup removeObject:deviceName];
            if([groupObj.audioGroup count] == 0)
            {
                [groupArr removeObject:groupObj];
            }
            
            [self addDevice:deviceName inGroup:groupName];
        }
    }
    else if([groupName length] != 0)
    {
        [self addDevice:deviceName inGroup:groupName];
    }
}

-(void)serviceAddAudioToGroupCallBack:(NSDictionary*)dicCallBack
{

}

@end
